#import "CTInfoVC.h"
#import "ZJScrollPageView.h"
#import "CTBasicVC.h"
#import "CTPersonalVC.h"
#import "CTContactVC.h"
#import "CTAuthModel.h"
#import "CTRefuseModel.h"
#import "CTRefuseView.h"
@interface CTInfoVC () <ZJScrollPageViewDelegate, UINavigationControllerDelegate>
@property(strong, nonatomic)NSArray<NSString *> *titles;
@property(strong, nonatomic)NSArray<UIViewController<ZJScrollPageViewChildVcDelegate> *> *childVcs;
@property (weak, nonatomic) ZJScrollSegmentView *segmentView;
@property (weak, nonatomic) ZJContentView *contentView;
@property (nonatomic, strong) UIView *bottomLine;
@property (nonatomic ,strong) UIImageView *segmentSelImgV;
@property (nonatomic ,strong) CTAuthModel *authModel;
@property (nonatomic ,strong) CTBasicVC *basicVC;
@property (nonatomic ,strong) CTPersonalVC *personVC;
@property (nonatomic ,strong) CTContactVC *contactVC;
@property (nonatomic ,assign) NSInteger currentIndex;
@property(nonatomic, copy) void(^submitResult)(BOOL isSuccess);
@end
@implementation CTInfoVC
- (instancetype)initWithResult:(void(^)(BOOL isSuccess))result {
    if (self = [super init]) {
        _submitResult = result;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.var_prohibitReturn = YES;
    [self setUI];
    [self requestRiskAuth];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
- (void)ct_navBackButtonClicked:(UIButton *)sender {
    if (self.currentIndex==0) {
        [self requestResuReason];
    } else {
        [self.segmentView setSelectedIndex:(self.currentIndex-1) animated:YES];
    }
}
- (void)setUI {
    self.title = @"";
    [self ct_showCustomerNavBarWithType:WBNavBarTypeNormal];
    self.var_navBar.var_titleLabel.text = @"";
    self.var_navBar.backgroundColor = [UIColor whiteColor];
    [self.view ct_addVerticalGradientLayerStartColor:RGBA(240, 241, 241, 1).CGColor endColor:UIColor.whiteColor.CGColor];
    self.titles = @[@"Basic",
                    @"Personal",
                    @"Contact"
                    ];
    self.childVcs = [self setupChildVc];
    [self setupSegmentView];
    [self setupContentView];
}
#pragma mark - refuse request
- (void)requestResuReason {
    [self.view showLoading];
    NSDictionary *paramDic = @{ 
        @"userGroup" : returnBeNil([CTUserManager shareManager].userModel.userGroup),
        @"layoutTemplateKind" : @(0),
    };
    [CTBaseRequest postRequestWithMethodName:CTPath(@"/getAuthOptions", CTPathTypePost, nil) parametersDic:paramDic success:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        [self.view dismissLoading];
        if (!isSuccess) {
            [self.view showInfoText:(NSString *)responseObject];
        } else {
            NSArray *refuseDatas = [CTRefuseModel modelArrayWithDictArray:responseObject[@"matterContent"]];
            CTRefuseView *refuseView = [[CTRefuseView alloc] init];
            refuseView.dataArray = refuseDatas;
            refuseView.reasonSelected = ^(NSString * _Nonnull content, BOOL isSuccess) {
                if (isSuccess) {
                    self.submitResult(NO);
                    [self.navigationController popViewControllerAnimated:YES];
                }
            };
            [refuseView show];
        }
    }];
}
#pragma mark - securityCheck
- (void)requestRiskAuth {
    [self.view showLoading];
    NSDictionary *paramDic = @{ @"userGroup" : returnBeNil([CTUserManager shareManager].userModel.userGroup),
                                @"productClassificationType" : @(1),
                                @"isCreditAcquisitionStatus" : @"0",
                                @"pageIdentity" : @"index",
                                @"refreshUrgentContactRoster" : @(0),
                                @"requiresCachingFlag" : @(0),
    };
    [CTBaseRequest postRequestWithMethodName:CTPath(@"/securityCheck", CTPathTypePost, nil) parametersDic:paramDic success:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        [self.view dismissLoading];
        if (!isSuccess) {
            [self.view showInfoText:(NSString *)responseObject];
        } else {
            CTAuthModel *model = [CTAuthModel modelWithDictionary:responseObject[@"matterContent"]];
            self.authModel = model;
            CTElementModel *creditElement = self.authModel.creditComponent;
            NSArray <CTPageElementModel *> *pageArray = creditElement.pageComponentParts;
            CTCreditModel *creditResult = [CTCreditModel mj_objectWithKeyValues:creditElement.creditAssessmentOutcome];
            if ([[CTUserManager shareManager].userModel.wirelessDeviceNumber isEqualToString:appTelPhone]) {
                NSString *path = [[NSBundle mainBundle] pathForResource:@"creditInfo" ofType:@"json"];
                NSData *jsonData = [[NSData alloc] initWithContentsOfFile:path];
                NSDictionary *creditDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
                CTCreditModel *creditResult = [CTCreditModel modelWithDictionary:creditDic];
                self.basicVC.pageModel = [pageArray objectAtIndex:0];
                self.basicVC.model = creditResult.personalProfileData;
                [self.basicVC.tableView reloadData];
                self.personVC.pageModel = [pageArray objectAtIndex:1];
                self.personVC.model = creditResult.communicationDetails;
                [self.personVC.tableView reloadData];
                self.contactVC.pageModel = [pageArray objectAtIndex:2];
                self.contactVC.model = creditResult.deferredActionTrigger;
                [self.contactVC.tableView reloadData];
            } else {
                self.basicVC.pageModel = [pageArray objectAtIndex:0];
                self.basicVC.model = creditResult.personalProfileData;
                [self.basicVC.tableView reloadData];
                self.personVC.pageModel = [pageArray objectAtIndex:1];
                self.personVC.model = creditResult.communicationDetails;
                [self.personVC.tableView reloadData];
                self.contactVC.pageModel = [pageArray objectAtIndex:2];
                self.contactVC.model = creditResult.deferredActionTrigger;
                [self.contactVC.tableView reloadData];
            }
        }
    }];
}
#pragma mark - submit all
- (void)submitAllData {
    NSDictionary *contactData = @{
        @"navigationRoute" : NSStringFromClass(self.class),
        @"pageIdentity" : kct_btn_contact_next,
        @"elementUniqueIdentifier"  : kct_btn_contact_next,
    };
    [CTUploadManager ct_uploadType:CTUploadTypeBTN data:contactData];
    NSDictionary *identityInfo = [self.basicVC.model mj_keyValues];
    [identityInfo setValue:@"" forKey:@"frontSideIDPhoto"];
    [identityInfo setValue:@"" forKey:@"reverseSideIDPhoto"];
    [identityInfo setValue:@"" forKey:@"liveCaptureImage"];
    NSDictionary *personInfo = @{
        @"academicAttainmentLevel" : self.personVC.model.academicAttainmentLevel.dataCategoryTag,
        @"employmentCondition" : self.personVC.model.employmentCondition.dataCategoryTag,
        @"occupationalRole" : self.personVC.model.occupationalRole.dataCategoryTag,
        @"monthlyEarningsReport" : self.personVC.model.monthlyEarningsReport.dataCategoryTag,
        @"maritalState" :self.personVC.model.maritalState.dataCategoryTag,
        @"dwellingCategory" : self.personVC.model.dwellingCategory.dataCategoryTag,
        @"residentialStateInfo" : self.personVC.model.residentialStateInfo.dataCategoryTag,
        @"residentialDistrictInfo" : self.personVC.model.residentialDistrictInfo.dataCategoryTag,
        @"residentialAddressDetails" : self.personVC.model.residentialAddressDetails,
        @"salaryDisbursementDate" : self.personVC.model.salaryDisbursementDate.dataCategoryTag,
        @"employmentCommencement" : self.personVC.model.employmentCommencement,
        @"corporateContactNumber" : self.personVC.model.corporateContactNumber,
        @"electronicMailbox" : self.personVC.model.electronicMailbox,
    };
    NSArray *contactsInfo = self.contactVC.contactArray;
    NSDictionary *data = @{
        @"submissionDenialStatus" : @(0),
        @"inactiveContactRecord" : @"",
        @"s3FileType" : @"",
        @"personalIdentityData" : identityInfo,
        @"personalInformationProfile" : personInfo,
        @"contactProfileData" : contactsInfo,
    };
    NSDictionary *submitData = @{
        @"operationalTaskID" : returnBeNil(self.authModel.creditComponent.pageComponentParts.firstObject.operationalTaskID),
        @"identifierCode" : @"20001",
        @"serverEndpointAddress" : @(0),
        @"data" : data,
    };
    NSDictionary *redisCreditDatas = @{
        @"personalProfileData" : [self.basicVC.model mj_JSONString],
        @"communicationDetails" : [self.personVC.model mj_JSONString],
        @"deferredActionTrigger" : [self.contactVC.model mj_JSONString],
    };
    NSDictionary *submitDic = @{
        @"userGroup" : returnBeNil([CTUserManager shareManager].userModel.userGroup),
        @"dataSubmissionRecord" : submitData,
        @"redisBasedCreditRecords" : redisCreditDatas,
    };
    [self.view showLoading];
    [CTBaseRequest postRequestWithMethodName:CTPath(@"/submitCreditApp", CTPathTypePost, nil) parametersDic:submitDic success:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        [self.view dismissLoading];
        if (!isSuccess) {
            [self.view showInfoText:(NSString *)responseObject];
        } else {
            [self requestResult];
        }
    }];
}
- (void)requestResult {
    NSDictionary *paramDic = @{ @"operationalTaskID": returnBeNil(self.authModel.creditComponent.pageComponentParts.firstObject.operationalTaskID), @"requestIdentifier": @"20002" };
    [self.view showLoading];
    [CTBaseRequest getRequestWithMethodName:CTPath(@"/grantingTaskState", CTPathTypeCredit, paramDic) parametersDic:paramDic success:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        [self.view dismissLoading];
        if (!isSuccess) {
        } else {
            if (responseObject[@"data"] != nil) {
                NSDictionary *data = responseObject[@"data"];
                if ([data[@"identifierCode"] isEqualToString:@"80000"]) {
                    NSDictionary *credtiData = @{
                        @"tokenUniqueIdentifier"  : returnBeNil(self.contactVC.pageModel.operationalTaskID),
                        @"errorFlag" : kpage_contactinfo_nextSucPoint,
                    };
                    [CTUploadManager ct_uploadType:CTUploadTypeCredit data:credtiData];
                    [CTAFManager logEvent:LC_auth_Success];
                    self.submitResult(YES);
                    [self.navigationController popViewControllerAnimated:YES];
                } else {
                    [self.view showText:returnBeNil(data[@"textualCommunication"])];
                }
            } else {
                [self requestResult];
            }
        }
    }];
}
#pragma mark - ZJScrollPageView
- (NSArray *)setupChildVc {
    CTElementModel *creditElement = self.authModel.creditComponent;
    NSArray <CTPageElementModel *> *pageArray = creditElement.pageComponentParts;
    CTCreditModel *model = [CTCreditModel mj_objectWithKeyValues:creditElement.creditAssessmentOutcome];
    __weak typeof(self) weakSelf = self;
    self.basicVC = [CTBasicVC new];
    self.basicVC.pageModel = [pageArray objectAtIndex:0];
    self.basicVC.model = model.personalProfileData;
    self.basicVC.nextClickBlock = ^{
        [weakSelf.segmentView setSelectedIndex:1 animated:YES];
    };
    self.personVC = [CTPersonalVC new];
    self.personVC.pageModel = [pageArray objectAtIndex:1];
    self.personVC.model = model.communicationDetails;
    self.personVC.nextClickBlock = ^{
        [weakSelf.segmentView setSelectedIndex:2 animated:YES];
    };
    self.contactVC = [CTContactVC new];
    self.contactVC.pageModel = [pageArray objectAtIndex:2];
    self.contactVC.model = model.deferredActionTrigger;
    self.contactVC.submitClickBlock = ^{
        if ([[CTUserManager shareManager].userModel.wirelessDeviceNumber isEqualToString:appTelPhone]) {
            weakSelf.submitResult(YES);
            [weakSelf.navigationController popViewControllerAnimated:YES];
        } else {
            [weakSelf submitAllData];
        }
    };
    NSArray *childVcs = [NSArray arrayWithObjects:self.basicVC, self.personVC, self.contactVC, nil];
    return childVcs;
}
- (void)setupSegmentView {
    ZJSegmentStyle *style = [[ZJSegmentStyle alloc] init];
    style.gradualChangeTitleColor = YES;
    style.showLine = YES;
    style.scrollTitle = NO; 
    style.adjustCoverOrLineWidth = YES;
    style.autoAdjustTitlesWidth = YES;
    style.selectedTitleColor = [UIColor color333];
    style.normalTitleColor = [UIColor color252525];
    style.scrollLineColor = [UIColor colorFF6C2E];
    style.scrollLineHeight = 2;
    style.titleFont = [UIFont systemFontOfSize:Ratio(16)];
    style.scrollContentView = NO;
    __weak typeof(self) weakSelf = self;
    ZJScrollSegmentView *segment = [[ZJScrollSegmentView alloc] initWithFrame:CGRectMake(Ratio(10),[UIDevice ct_fullNavHeight]+Ratio(14), kScreenWidth-Ratio(20), Ratio(52)) segmentStyle:style delegate:self titles:self.titles titleDidClick:^(ZJTitleView *titleView, NSInteger index) {
        [weakSelf.contentView setContentOffSet:CGPointMake(weakSelf.contentView.bounds.size.width * index, 0.0) animated:YES];
    }];
    segment.userInteractionEnabled = NO;
    segment.backgroundImage = [UIImage imageNamed:@"info_bg"];
    UIImageView *backgroundImageView = [segment valueForKey:@"backgroundImageView"];
    [segment insertSubview:self.segmentSelImgV aboveSubview:backgroundImageView];
    self.segmentView = segment;
    [self.view addSubview:segment];
}
- (void)setupContentView {
    ZJContentView *content = [[ZJContentView alloc] initWithFrame:CGRectMake(self.segmentView.ct_left, self.segmentView.ct_bottom, self.view.ct_width-Ratio(20), kScreenHeight-self.segmentView.ct_bottom) segmentView:self.segmentView parentViewController:self delegate:self];
    self.contentView = content;
    self.contentView.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.contentView];
}
#pragma mark - ZJScrollPageViewDelegate
- (void)setUpTitleView:(ZJTitleView *)titleView forIndex:(NSInteger)index {
    NSString *title = [self.titles objectAtIndex:index];
    titleView.text = title;
}
- (BOOL)shouldAutomaticallyForwardAppearanceMethods {
    return NO;
}
- (NSInteger)numberOfChildViewControllers {
    return self.titles.count;
}
- (UIViewController<ZJScrollPageViewChildVcDelegate> *)childViewController:(UIViewController<ZJScrollPageViewChildVcDelegate> *)reuseViewController forIndex:(NSInteger)index {
    UIViewController<ZJScrollPageViewChildVcDelegate> *childVc = reuseViewController;
    if (!childVc) {
        childVc = [self.childVcs objectAtIndex:index];
    }
    return childVc;
}
- (void)scrollPageController:(UIViewController *)scrollPageController childViewControllWillAppear:(UIViewController *)childViewController forIndex:(NSInteger)index {
    NSString *title = [self.titles objectAtIndex:index];
    self.var_navBar.var_titleLabel.text = title;
    self.currentIndex = index;
}
- (void)scrollPageController:(UIViewController *)scrollPageController childViewControllDidAppear:(UIViewController *)childViewController forIndex:(NSInteger)index {
    NSString *imageName = [NSString stringWithFormat:@"info_%ld", index];
    self.segmentSelImgV.image = [UIImage imageNamed:imageName];
}
- (UIView *)bottomLine {
    if (!_bottomLine) {
        _bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0, self.segmentView.ct_height-0.5, self.view.ct_width, 1)];
        _bottomLine.backgroundColor = [UIColor colorDDD];
    }
    return _bottomLine;
}
- (UIImageView *)segmentSelImgV {
    if (!_segmentSelImgV) {
        _segmentSelImgV = [[UIImageView alloc] init];
        _segmentSelImgV.image = [UIImage imageNamed:@"info_0"];
        _segmentSelImgV.frame = CGRectMake(0, Ratio(-2), kScreenWidth-Ratio(20), Ratio(65));
    }
    return _segmentSelImgV;
}
@end
